import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:star_author/model/push_msg_info_entity.dart';
import 'package:star_author/utils/common_util/log_util.dart';

class PushMsgHandler {
  String getMsgCount(int msgCount) {
    return msgCount > 99 ? '99+' : msgCount.toString();
  }

  /// 推送格式：
  /// Android:
  /// {
  ///  extras: {
  ///    cn.jpush.android.ALERT_TYPE: 7,
  ///    cn.jpush.android.EXTRA: {
  ///      "subType":"2",
  ///      "type":"1"
  ///      },
  ///    cn.jpush.android.MSG_ID: 2251831944818682,
  ///    cn.jpush.android.ALERT: 测试推送内容,
  ///    cn.jpush.android.NOTIFICATION_ID: 464651081
  ///  },
  ///  alert: "测试推送内容",
  ///  title: "测试推送"
  /// }
  /// iOS:
  /// {
  ///    extras: {
  ///        type: 1, subType: 2
  ///    },
  ///    subType: 2,
  ///    _j_uid: 32406415798,
  ///    _j_msgid: 29273429984737555,
  ///    aps: {
  ///        alert: {
  ///            title: "测试iPhone",
  ///            body: "测试iPhone"
  ///        },
  ///        badge: 1,
  ///        sound: default
  ///    },
  ///    _j_business: 1,
  ///    type: 1
  /// }
  ///{

  //iOS
  //     "_j_business" = 1;
  //     "_j_data_" = "{\"data_msgtype\":1,\"push_type\":4,\"is_vip\":0}";
  //     "_j_msgid" = 18100112738703651;
  //     "_j_uid" = 61586056065;
  //     aps =     {
  //         alert =         {
  //             body = "\U6d88\U606f\U5185\U5bb92";
  //             title = "\U8df3\U8f6c\U9996\U9875\U63a8\U9001";
  //         };
  //         badge = 8;
  //         "mutable-content" = 1;
  //     };
  //     jumpPath = "intent:#Intent;action=android.intent.action.MAIN;end";
  // }

  PushMsgInfoEntity convertJPMsg2PushMsgInfo(Map<String, dynamic> message) {
    late PushMsgInfoEntity pushMsgInfo;

    try {
      if (Platform.isIOS) {
        Map alert = message['aps']['alert'];
        String jumpPath = message['jumpPath'];
        String action = message['action'];

        pushMsgInfo = PushMsgInfoEntity.fromJson({
          "msgId": message['_j_msgid'].toString(),
          "title": alert['title'],
          "content": alert['body'],
          "jumpPath": jumpPath,
          "action": action,
        });
      } else if (Platform.isAndroid) {
        Map extras = message['extras'];
        Map extra = json.decode(extras['cn.jpush.android.EXTRA']);
        String jumpPath = extra["jumpPath"];
        String action = extra["action"];

        pushMsgInfo = PushMsgInfoEntity.fromJson({
          "msgId": extras['cn.jpush.android.MSG_ID'].toString(),
          "title": message['title'],
          "content": message['alert'],
          "jumpPath": jumpPath,
          "action": action,
        });
      }
    } catch (e) {
      LogUtil.e('convert jp msg 2 push msg info error------->$e');
    }

    return pushMsgInfo;
  }

  /// 更新推送消息信息
  void updatePushInfo(BuildContext context,
      {bool isShowNotification = false}) {}
}
